<?php
/**
 * API公共基类
 */
class ApiCommonApp extends Controller{
	
	/**
	 * 接口错误码
	 * @var array
	 */
	protected static $apiCodes = array();
	
	
	/**
	 * 用户信息数组
	 * @var array
	 */
	protected static $userInfo = null;
	
	
	/**
	 * 初始化
	 */
	public function _initialize(){
		header('Content-Type:text/html;charset=utf-8');
		$codeArr = config('api_error_code');
		if(is_array($codeArr))
		{
			foreach ($codeArr as $valArr)
			{
				foreach ($valArr as $k=>$v)
				{
					self::$apiCodes[$k] = $v;
				}
			}     
		}
		self::$userInfo = $_SESSION;
		$this->checkLogin();
	}
	
	
	/**
	 * 检测是否登录
	 * @param string $controllerName 控制器名称
	 * @return bool
	 */
	public function checkLogin($controllerName = CONTROLLER_NAME, $actionName = ACTION_NAME)
	{
		$controllerName = strtolower($controllerName);
		$actionName = strtolower($actionName);
		
		// 可公共访问的控制器及相关的Action
		$authArr = array(
						'user'=>array('login','register','oauth2login','binding_user','login_employee'),
						'client'=>array('index'), 'behavior'=>array('add')
						);
		if(array_key_exists($controllerName, $authArr))
		{
			$accessArr = $authArr[$controllerName];
			if(in_array($actionName, $accessArr)) return true;
		}
		if(!self::$userInfo) 
		{
			$this->formatReturn(205);
		}
		return true;
	}
	
	
	/**
	 * json格式返回
	 */
	public function jsonReturn($data){
		exit(json_encode($data));
	}
	
	/**
	 * xml格式返回
	 */
	public function xmlReturn($data){
		$data = array('root'=>$data);
		header('Content-Type:text/xml;charset=utf-8');
		exit(XML::XML_serialize($data));
	}
	
	/**
	 * 按照某种格式返回数据
	 */
	public function formatReturn($code, $list=''){
		$message = isset(self::$apiCodes[$code])?self::$apiCodes[$code]:'';
		$data = array('header'=>array('statusCode'=>$code, 'message'=>$message));
		if(!empty($list)){
			$data['body']['data'] = $list;
		}
		if(My::arr2var($_REQUEST,'format') == 'xml'){
			$this->xmlReturn($data);
		}else{
			$this->jsonReturn($data);
		}
	}

}